let _Vue = null


export default class VueRouter {
    constructor(options) {
        this.options = options
        this.routeMap = {}
        this.data = _Vue.observable({
            current: '/'
        })
    }

    static install(Vue) {
        // 防止二次注册
        if (VueRouter.install.installed) return

        VueRouter.install.installed = true

        _Vue = Vue

        // 为了给所有的vue实例挂载一个$router对象,而且这个对象的值是vue实例上的router
        // 直接_Vue.prototype.$router = this.$options.router无法获取vue实例
        // 所以这里采用了混入的方式给每个实例都加上一个对象,但因为$router是继承对象,又要符合mixin的写法
        // 所以这里把关键代码写到beforeCreate钩子上
        _Vue.mixin({
            beforeCreate() {
                // Vue实例执行,组件不执行
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }

    init() {
        this.createRouteMap()
        this.initComponents(_Vue)
        this.initEvent()
    }

    createRouteMap() {
        this.options.routes.forEach(async (route) => {
            let component = null
            if (route.component instanceof Promise) {
                component = (await route.component).default
            } else {
                component = route.component
            }
            this.routeMap[route.path] = component
        })
        console.log(this.routeMap);
    }


    initComponents(Vue) {

        Vue.component('router-link', {
            props: {
                to: String,
                tag: String,
            },
            render(h) {
                return h(this.tag || 'a', {
                    href: this.to,
                    on: {
                        click: (e) => {
                            e.preventDefault();
                            history.pushState(null, '', this.to)
                            // 给实例
                            this.$router.data.current = this.to
                        }
                    }
                }, [this.$slots.default])
            }
        })

        let self = this
        Vue.component('router-view', {
            render(h) {
                return h(self.routeMap[self.data.current])
            }
        })
    }

    initEvent() {
        // 处理前进后退
        window.addEventListener('popstate', () => {
            this.data.current = window.location.pathname
        })
    }
}